package com.web.webstart.base.security;


import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.entity.User;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.webstart.base.util.result.XaResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: XaRememberLastUsernameAuthenticationSuccessHandler
 * @Description:
 * @author dazer
 * @date 2017/3/13 上午12:22
 */ 
public class XaRememberLastUsernameAuthenticationSuccessHandler extends
        SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ApiUserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication)
            throws ServletException, IOException {
        this.handleUsername(response, authentication);

        String username = this.getUsername(authentication);
        User user = userService.validUserName(username);

        //rentongtong  dazer 支持登录json接口形式 2017.02.16 begin
        if (request.getParameter("datatype") != null && request.getParameter("datatype").equals("json")) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");

            XaResult xr = new XaResult();
            xr.success(user);
            xr.setMessage("登录成功！");

            response.getWriter().println(JSON.toJSON(xr));

            response.getWriter().flush();
            new HttpSessionRequestCache().removeRequest(request, response);
            clearAuthenticationAttributes(request);
            return;
        }
        //rentongtong  dazer 支持登录json接口形式 2017.02.16 end

        super.onAuthenticationSuccess(request, response, authentication);
    }


    public void handleUsername(HttpServletResponse response,
                               Authentication authentication) {
        String username = this.getUsername(authentication);
        this.addCookie(response, XaSecurityConstants.SECURITY_LAST_USERNAME,
                username);
    }


    public void addCookie(HttpServletResponse response, String key, String value) {
        this.addCookie(response, key, value, 3600 * 24 * 30);
    }

    public void addCookie(HttpServletResponse response, String key,
                          String value, int maxAge) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    public String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();

        if (cookies == null) {
            return null;
        }

        for (Cookie cookie : cookies) {
            if ((cookie == null) || (cookie.getName() == null)) {
                continue;
            }

            if (cookie.getName().equals(key)) {
                return cookie.getValue();
            }
        }

        return null;
    }

    public String getUsername(Authentication authentication) {
        if (authentication == null) {
            return "";
        }

        Object principal = authentication.getPrincipal();

        if (principal instanceof XaUserDetails) {
            return ((XaUserDetails) principal).getUsername();
        } else {
            return authentication.getName();
        }
    }

}
